package cn.janescott.file.server.processor;

import cn.janescott.file.server.dto.FileInfoDTO;
import cn.janescott.file.server.exception.MyException;
import cn.janescott.file.server.exception.MyExceptionEnums;
import cn.janescott.file.server.util.IoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 文件操作
 *
 * @author scott
 * @date 2019/4/15
 */
public class BinaryProcessor {
    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 存储目录
     */
    private String dir = "/dir";

    /**
     * 缓冲区大小
     */
    private int bufferSize = 1024;

    public void setDir(String dir) {
        this.dir = dir;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    /**
     * 文件上传
     *
     * @param part
     * @return
     */
    public FileInfoDTO upload(Part part) {
        try {
            System.out.println(part);
            FileInfoDTO info = new FileInfoDTO();
            info.setContentType(part.getContentType());
            info.setName(part.getName());
            info.setUploader("system");
            String path = generatePath(part.getName());
            File target = new File(dir + File.separator + path, part.getName());
            try (FileOutputStream out = new FileOutputStream(target)) {
                IoUtil.transfer(part.getInputStream(), out, bufferSize);
            }
            return info;
        } catch (SecurityException se) {
            logger.error(se.getMessage(), se);
            throw MyException.failed(MyExceptionEnums.NOT_WRITE_PERMISSION, se);
        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
            throw MyException.failed(MyExceptionEnums.IO_EXCEPTION, ioe);
        }
    }

    /**
     * 生成文件路径
     *
     * @param filename
     * @return
     */
    private String generatePath(String filename) {
        LocalDateTime date = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd(HH-mm-ss)");
        String prefix = date.format(formatter);
        return prefix + filename;
    }

}
